package Day2025_02_20;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LeetCode30 {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> list = new ArrayList<>();
        char[] ch = s.toCharArray();
        int n = ch.length;
        int kinds = words.length;
        int len = words[0].length();
        Map<String, Integer> hash1 = new HashMap<>();
        Map<String, Integer> hash2 = new HashMap<>();
        for (String str : words) hash2.put(str, hash2.getOrDefault(str, 0) + 1);
        for (int left = 0, right = 0; right < n - len; right++) {
            while (right < n - len) {
                String in = s.substring(right, right + len);
                hash1.put(in, hash1.getOrDefault(in, 0) + 1);
                if (hash1.get(in) <= hash2.getOrDefault(in, 0)) kinds--;
                if (kinds == 0) list.add(left);
                if (right - left + 1 == kinds * len) {
                    String out = s.substring(left, left + len);
                    hash1.put(out, hash1.get(out) - 1);
                    left += len;
                    if (hash1.get(out) <= hash2.get(out)) kinds++;
                }
                right += len;
            }
        }
        return list;
    }

    public static void main(String[] args) {
        LeetCode30 leetCode30 = new LeetCode30();
        System.out.println(leetCode30.findSubstring("barfoothefoobarman", new String[]{"foo", "bar"}));
    }
}
